<template>
  <div style="width: 100%; height: 100%">
    <!-- 查询框 -->
    <div>
      <el-tag >用户名</el-tag>
      <el-input v-model="keyword" style="width: 300px; margin-left: 10px; margin-right: 10px" placeholder="请输入关键词"></el-input>
      <el-button type="primary" @click="fetchAccounts">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>

    <!-- 操作框 -->
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <!-- 账号列表 -->
    <!-- 表格 -->
    <div style="margin: 10px 0">
      <el-table :data="accounts" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="user_id" label="序号" width="70" align="center"></el-table-column>
        <el-table-column prop="username" label="账号名称"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role" label="角色">
          <template slot-scope="scope">
          {{ roleWacth(scope.row.role) }}
        </template>
        </el-table-column>
        <el-table-column label="详细信息">
          <template slot-scope="scope" >
            <span v-if="scope.row.role=='admin'">
            </span>
            <span v-else>
              <el-button size="mini" type="primary" plain @click="handwatch(scope.row)">查看{{roleWacth(scope.row.role)}}详细信息</el-button>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.user_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

<!--    企业信息窗口-->
    <el-dialog :title="NewDialogTitle" :visible.sync="BossDialogVisible" width="30%" >
      <el-form :model="bossItem" label-width="100px" :rules="rule">

        <el-form-item label="公司名称">
          <el-input v-model="bossItem.company_name" ></el-input>
        </el-form-item>
        <el-form-item label="行业">
          <el-input v-model="bossItem.industry" ></el-input>
        </el-form-item>
        <el-form-item label="网站">
          <el-input v-model="bossItem.website" ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="bossItem.description" type="textarea" rows="3" ></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="bossItem.contact_person" ></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱">
          <el-input v-model="bossItem.contact_email" ></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="bossItem.contact_phone" ></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="bossItem.address" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>

<!--    //学生信息窗口-->
    <el-dialog :title="NewDialogTitle" :visible.sync="StuDialogVisible" width="30%" >
      <el-form :model="StuItem" label-width="100px" :rules="rule">

        <el-form-item label="姓名">
          <el-input v-model="StuItem.name" ></el-input>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="StuItem.dob" type="date" ></el-date-picker>
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="StuItem.gender" ></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="StuItem.phone" ></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="StuItem.address" ></el-input>
        </el-form-item>
        <el-form-item label="简历">
          <el-input v-model="StuItem.resume" type="textarea" rows="3" ></el-input>
        </el-form-item>
        <el-form-item label="教育背景">
          <el-input v-model="StuItem.education" type="textarea" rows="3" ></el-input>
        </el-form-item>
        <el-form-item label="工作经验">
          <el-input v-model="StuItem.experience" type="textarea" rows="3" ></el-input>
        </el-form-item>
        <el-form-item label="技能">
          <el-input v-model="StuItem.skills" type="textarea" rows="3" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑账号模态框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" >
      <el-form :model="editItem" label-width="100px" :rules="rule">
        <el-form-item label="账号名称">
          <el-input v-model="editItem.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" show-password v-model="editItem.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input type="email" v-model="editItem.email"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editItem.role" placeholder="请选择角色">
            <el-option label="学生" value="student"></el-option>
            <el-option label="企业" value="company"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">{{ isEditing ? '保存' : '新增' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";


export default {
  data() {
    return {
      student:'',
      searchAccount: '',
      searchuser: {
        username: '',
        email:'',
      },
      UserIfos:[],
      accounts: [], // 账号信息列表
      StuData:[],
      BossDta:[],
      currentPage: 1, // 当前页数
      pageSize: 5, // 每页显示的条数
      totalItems: 0, // 总条数
      searchType: '用户名', // 默认查询类型
      keyword: '', // 查询关键词
      dialogVisible: false, // 账号信息模态框可见性
      editItem: { // 编辑/新增的数据
        user_id:'',
        username: '',
        password: '',
        role: '',
        email:'',
        company_name:'企业',
        name:'学生',
        experience:'无',
      },
      AddFormItem:{},
      StuItem: {},
      bossItem:{},
      userExists:false,
      isEditing: false, // 是否为新增模式
      StuDialogVisible: false,
      BossDialogVisible:false,
      isRoleTing:false,
      AddSta:false,
      rule:{
        email:[
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      return this.isEditing ? '编辑信息' : '新增信息'; //false为新增，true为编辑
    },
    NewDialogTitle() {
      return this.isRoleTing ? '学生信息' : '企业信息'; //false为企业，true为学生
    }
  },
  mounted() {
    this.fetchAccounts();
  },
  methods: {
    roleWacth(role){
      if (role==='admin'){
        return '管理员';
      }
      if (role==='company'){
        return '企业';
      }
      if (role==='student'){
        return '学生';
      }
    },
    handwatch(row){
      if (row.role==='student'){
        let StuDta= this.StuData.filter(item => item.user_id === row.user_id);
        this.StuItem=StuDta[0]
        this.StuDialogVisible=true;
        this.isRoleTing=true;
      }
      if(row.role==='company'){

        let BossData= this.BossDta.filter(item => item.user_id === row.user_id);
        this.bossItem=BossData[0]
        console.log(this.bossItem)
        this.BossDialogVisible=true;
        this.isRoleTing=false;
      }

    },
    // 获取账号信息
    fetchAccounts() {
      let url = 'http://localhost:8080/User/selectAll';
      let params = {
        page: this.currentPage,
        size: this.pageSize
      };


      if (this.keyword) {
        // 如果输入了关键词，则根据选择的查询条件发送相应的请求
        // 构建带查询参数的URL

        axios.get('http://localhost:8080/User/selectByUsername', {
          params: {
            username: this.keyword
          }
        })
            .then(response => {
              this.accounts = response.data.data;
            })
            .catch(error => {
              console.error('Error fetching accounts:', error);
            });

      }else {
        axios.get(url,{ params } )
            .then(response => {
              const data = response.data.data;
              this.accounts = data;
              this.totalItems = data.length;
            })
            .catch(error => {
              console.error('Error fetching accounts:', error);
            });
      }
      this.findStuAll();
      this.findBossAll();
    },
    reset() {//重置
      this.searchType = '用户名';
      this.keyword = '';
      this.currentPage = 1;
      this.pageSize = 5;
      this.fetchAccounts();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchAccounts();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchAccounts();
    },
    AddForm(){
      this.AddFormItem=this.editItem;
      axios.get('http://localhost:8080/User/selectAll').then(response => {
        this.searchuser = response.data.data;
        if(this.AddSta===true){
          this.UserIfos=response.data.data;
          for (let user of this.UserIfos) {
            if (user.username === this.AddFormItem.company_name||user.username === this.AddFormItem.name) {
              this.AddFormItem.user_id=user.user_id;
            }
          }
          console.log(this.AddFormItem.role)
          if(this.AddFormItem.role === 'student'){
            this.addStu();
          }else if(this.AddFormItem.role === 'company'){
            this.addBoss();
          }else if(this.AddFormItem.role === 'admin'){
            this.AddSta=false;
          }
        }
        if(this.AddSta===false&&this.userExists===false) {
          for (let user of this.searchuser) {
            if (user.username === this.AddFormItem.username) {
              this.userExists = true;
              break;
            }
            if (user.email === this.AddFormItem.email) {
              this.userExists = true;
              break;
            }
          }
          if (!this.userExists) {
            this.userExists=true;
            this.handleAdd();
          } else {
            console.log('error submit!!');
            this.$message.error("注册失败，用户已存在");
          }
        }

      })
          .catch(error => {
            console.error('Error fetching users:', error);
            this.$message.error("获取用户信息失败");
          });

    },
    findStuAll(){
      axios.get("http://localhost:8080/User/selectStuAll") .then(response => {
            this.StuData = response.data.data;
      })
          .catch(error => {
            console.error('Error fetching accounts:', error);
          });
    },
    findBossAll(){
      axios.get("http://localhost:8080/User/selectBossAll") .then(response => {
        this.BossDta = response.data.data;
        console.log(this.BossDta)
      })
          .catch(error => {
            console.error('Error fetching accounts:', error);
          });
    },
    handleSelectionChange(val) {//选择的行
      this.selectedRows = val.map(row => row.user_id);
    },
    showAddDialog() {
      this.isEditing = false;
      this.editItem = { // 新增表单置空
        username: '',
        password: '',
        role: '',
        email:'',
        company_name:'企业',
        name:'学生',
        experience:'无',
      };
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.isEditing = false;
      this.BossDialogVisible=false;
      this.StuDialogVisible=false;
      this.isRoleTing=false;
    },
    handleAdd() {
      // 实现新增功能的逻辑
      axios.post("http://localhost:8080/User/add", this.editItem)
          .then(response => {
            if(this.editItem.role === 'student'){
              this.editItem.name=this.editItem.username;
            }else if(this.editItem.role === 'company'){
              this.editItem.company_name=this.editItem.username;
            }
            console.log(this.editItem)
            this.AddSta=true;
            this.AddForm();
            // 处理新增成功逻辑
            this.$message.success("新增成功");
            this.dialogVisible = false;
            this.fetchAccounts(); // 刷新数据
          })
          .catch(error => {
            // 处理新增失败逻辑
            console.error('Error adding new item:', error);
            this.$message.error("新增失败");
          });

    },
    handleEdit(row) {
      // 将选中行的数据赋值给编辑的数据项
      this.editItem = Object.assign({}, row);
      // 设置编辑状态为true
      this.isEditing = true; // 设置编辑状态为true，表示编辑
      // 打开新增/编辑弹窗
      this.dialogVisible = true;
    },
    handleSaveEdit() {
      // 发送编辑/新增请求到后端
      if (this.isEditing) {

        // 编辑状态下发送编辑请求
        axios.put("http://localhost:8080/User/edit", this.editItem)
            .then(response => {
              // 处理编辑成功逻辑
              this.$message.success("编辑成功");
              this.closeDialog();
              this.fetchAccounts(); // 刷新数据
            })
            .catch(error => {
              // 处理编辑失败逻辑
              console.error('Error editing item:', error);
              this.$message.error("编辑失败");
            });
      } else {
        this.userExists=false;
        // 新增状态下发送新增请求
        this.AddForm();
      }
    },
    handleDelete(user_id) {
      this.$confirm('此操作将永久删除该条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/User/deleteBossUser/${user_id}`)
        axios.delete(`http://localhost:8080/User/deleteStuUser/${user_id}`)
        axios.delete(`http://localhost:8080/User/deleteUser/${user_id}`)
            .then(response => {
              this.$message.success('删除成功');
              this.fetchAccounts(); // 刷新数据
            })
            .catch(error => {
              console.error('Error deleting item:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    delBatch() {
      // 确认是否删除选中的行
      this.$confirm('此操作将永久删除所选条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(this.selectedRows)
        // 批量删除操作
        axios.delete(`http://localhost:8080/User/deleteBatch`, {  data: this.selectedRows })
            .then(response => {
              this.$message.success('批量删除成功');
              this.fetchAccounts(); // 刷新数据
              this.selectedRows = []; // 清空选中的行
            })
            .catch(error => {
              console.error('Error deleting batch:', error);
              this.$message.error('批量删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消批量删除');
      });
    },
    addStu(){
      axios.post('http://localhost:8080/User/addStu',this.editItem).then(response => {
        this.dialogVisible = false;
        this.AddSta=false;
      })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
    addBoss(){
      axios.post('http://localhost:8080/User/addBoss',this.editItem).then(response => {
        this.dialogVisible = false;
        this.AddSta=false;
      })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },

  }
};
</script>

<style scoped>
.table-container {
  margin-top: 20px;
}
</style>

